﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.IO;

namespace iPdf
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            //set exception hanle mode
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            Process[] processes = Process.GetProcessesByName(Global.ProcessName);
            bool onlyInstance =  processes == null || processes.Length < 2;
            Task task = Helper.AnalyzeArguments(args);
            if (!onlyInstance)
            {
                IntPtr hwndFirstInstance = WinApi.FindWindow(null, Global.ApplicationName); // For FindWindow to work, applicationName must be the same as the title (the Text property) of your MainForm.
                WinApi.PostMessage(
                    hwndFirstInstance,
                    WinApi.WM_SHOWFIRSTINSTANCE,
                    IntPtr.Zero,
                    IntPtr.Zero);

                TaskProcessor.Notify(task);
                return;
            }

            TaskQueue.AddTask(task);

            TaskProcessor.Listen();
            
            //set the exception handler
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            //TODO
            Global.Cleanup();
            Application.Exit();
        }

    }
}
